package cn.woniu.ecommerceplatform.service;

import cn.woniu.ecommerceplatform.entity.Authentication;
import cn.woniu.ecommerceplatform.entity.NewUser;
import cn.woniu.ecommerceplatform.entity.Users;
import cn.woniu.ecommerceplatform.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SecurityServicce implements UserDetailsService {

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;
    @Autowired(required = false)
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username，去数据库查该用户的信息

        try {
            Users users = userMapper.queryUserInfoAndAuths(username);
            List<Authentication> auths1 = users.getAuths();
            List<String> authCodes=new ArrayList<>();
            for (Authentication authentication : auths1) {
                authCodes.add(authentication.getAuthCode());
            }
            String auths = String.join(",",authCodes);
            return new NewUser(users.getAccount(),passwordEncoder.encode(users.getPassword()),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(auths),users.getUserType());
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户名或密码有误");
        }
        //根据查出来的用户信息，荷叶面传过来的username,password做对比
    }
}
